package services;

import http.CaptchaForm;
import http.CaptchaPageParserStrategy;
import http.Link;
import http.Page;
import java.io.IOException;
import java.util.Map;
import java.util.Stack;

public class CaptchaService {
	private ICaptchaSolver solver;
	private Stack<Page> captchaPages = new Stack<Page>();
	private CaptchaPageParserStrategy captchastrategy;
	private static CaptchaService instance;
	private CaptchaService() {
	}
	public static CaptchaService getInstance() {
		if (instance == null)
			instance = new CaptchaService();
		return instance;
	}
	public void setSolver(ICaptchaSolver solver) {
		this.solver = solver;
	}
	public void addDownload(String link, String name) {
		try {
			captchaPages.push(new Page(link));
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
	private void retrieveCaptcha(Page captchaPage) {
		captchastrategy = new CaptchaPageParserStrategy();
		captchaPage.addParser(captchastrategy);
		try {
			captchaPage.open();
			if (captchastrategy.isParseable()) {
				Link captcha = captchastrategy.getCaptcha();
				solver.setCaptchaImage(captcha.toString());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void retrieveCaptcha() {
		if (captchaPages.size() > 0) {
			Page captchaPage = captchaPages.pop();
			retrieveCaptcha(captchaPage);
		}
	}
	public void setCaptchaCode(String t) {
		CaptchaForm cf = captchastrategy.getCaptchaForm();
		cf.solveCaptcha(t);
		try {
			Map<String,String> downloadList = CategoryService.getInstance().getDownloads(cf);
			System.out.println("CaptchaService::setCaptchaCode("+t+" Register "+downloadList.size()+" Downloads");
			DownloadListService.getInstance().addPartedDownload(downloadList);
			retrieveCaptcha();
		} catch (WrongCaptchaCodeException e) {
			retrieveCaptcha(e.getParsedPage());
		}
	}
}
